<script setup lang="ts">
/**
 * @name RemoteRealtimeMonitor
 * @description 远程实时监控
 */
import { Search } from '@element-plus/icons-vue'
import type { Point } from '@/components/ReadonlyPointTree/ReadonlyPointTree'
import { useRemoteRealtimeMonitor } from '@/mixins/RemoteMonitoringManagement/MixinRemoteRealtimeMonitor'
import { CONTAIN_SUB } from '@/enum/modules/public'
import type { EnergyBindItem } from '@/types'
import IndicatorDataCurveModal from '@/components/IndicatorDataCurveModal/IndicatorDataCurveModal.vue'
import { ParameterSetting, type ParameterSettingInstance } from './components/ParameterSetting'

const indicatorDataCurveModalRef = ref<InstanceType<typeof IndicatorDataCurveModal>>()
const indicatorNumber = ref<string>()

const parameterSettingRef = ref<ParameterSettingInstance>()

const { form } = useKeepPageStore()

form(['/dictionary-management'])

const [point, setPoint] = useState<Point | null>(null)
const level = ref(CONTAIN_SUB.NO_SUB)
const [energyType, setEnergyType] = useState<string | undefined>(undefined)
const {
  columns,
  lists,
  setLists,
  loading,
  pagination,
  getRealTimeMonitorData,
} = useRemoteRealtimeMonitor()

const [energyData, setEnergyData] = useState<
  EnergyBindItem[]
>([])
const energyName = computed(() => {
  return unref(energyData).find(item => item.code === unref(energyType))?.name
})
async function getEnergyData() {
  const pointId = unref(point)?.id
  if (!pointId) {
    setEnergyData([])
    return
  }
  const { data: res }
    = await energyApi.selectEnergy(pointId, unref(level))
  setEnergyData(res)
}

function handleClickNode(o: Point) {
  setPoint(o)
}
async function clickSearch() {
  pagination.pageNumber = 1
  await nextTick()
  getData()
}

async function handleOk(result: any) {
  pagination.pageNumber = 1
  await nextTick()
  getData(result)
}

function hasParam() {
  return unref(columns).some(item => item.prop === 'params')
}

async function getData(result?: any) {
  const pointId = unref(point)?.id
  const energyCode = unref(energyType)
  if (pointId && energyCode) {
    await getRealTimeMonitorData({
      energyCode,
      containSub: unref(level),
      pointId,
      pageSize: pagination.pageSize!,
      pageNumber: pagination.pageNumber,
      paramList: result
        ? result.map((v: any) => ({
          indicatorName: v.indicatorName,
          measuringPointNumber: v.measuringPointNumber,
        }))
        : null,
    })
    if (!hasParam()) {
      parameterSettingRef.value?.open()
    }
  }
  else {
    setLists([])
    pagination.total = 0
  }
}

async function clickValue(code: string) {
  indicatorNumber.value = code
  await nextTick()
  indicatorDataCurveModalRef.value?.showModal()
}

async function clickLink() {
  parameterSettingRef.value?.open()
}

function handleChangeEnergyType() {
  clickSearch()
}

watch([
  () => unref(point)?.id,
  () => unref(level),
], async () => {
  await getEnergyData()
  // 每次查询能源品种后清空历史值
  setEnergyType(
    unref(energyData)[0]?.code,
  )
  await nextTick()
  clickSearch()
})

onMounted(async () => {
  await getEnergyData()
  const t = unref(energyData)[0]?.code
  if (t) {
    setEnergyType(t)
    await nextTick()
    await getData()
  }
})
</script>

<template>
  <div class="padding-sm flex container">
    <div class="points-container">
      <ReadonlyPointTree fire @click-node="handleClickNode" />
    </div>
    <div class="margin-left-sm flex-fillRemaining roll flex-direction flex">
      <div class="flex flex-shrink-0 items-center">
        <ContainSubRadio v-model="level" />
        <span style="font-size: 14px;margin-left: 20px;">能源品种：</span>
        <ElSelect v-model="energyType" placeholder="请选择" style="max-width: 200px" @change="handleChangeEnergyType">
          <ElOption v-for="item in energyData" :key="item.code" :label="item.name" :value="item.code" />
        </ElSelect>
        <ElLink class="ml-auto mr-4" :disabled="!energyType" @click="clickLink">
          参数设置
        </ElLink>
        <ElButton type="primary" :icon="Search" @click="clickSearch">
          查询
        </ElButton>
      </div>
      <div class="roll mt-4 flex-1">
        <ElTable
          v-loading="loading" :data="lists"
          element-loading-custom-class="global-loading"
          height="100%"
        >
          <template #empty>
            <TableEmpty />
          </template>
          <ElTableColumn
            v-for="({ children, ...column }, index) in columns" :key="index" v-bind="column"
            :fixed="index < 2"
            :width="index < 2 ? 150 : undefined"
          >
            <template v-if="children && children.length > 0">
              <ElTableColumn v-for="(child, idx) in children" :key="idx" v-bind="child">
                <template #default="scope">
                  <ElTooltip
                    v-if="scope.row[child.prop] !== '-' && scope.row[`${child.prop}_time`] && scope.row[`${child.prop}_indicatorNumber`]"
                    placement="top" :content="scope.row[`${child.prop}_time`]"
                  >
                    <ElLink type="primary" @click="clickValue(scope.row[`${child.prop}_indicatorNumber`])">
                      <code>{{ scope.row[child.prop] }}</code>
                    </ElLink>
                  </ElTooltip>
                  <code v-else>{{ scope.row[child.prop] }}</code>
                </template>
              </ElTableColumn>
            </template>
            <template v-if="column.prop === 'status'" #default="{ row }">
              <ElTag :type="row.status === '正常' ? 'success' : 'danger'">
                {{ row.status }}
              </ElTag>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <ListsPagination
        v-model:page-num="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        class="self-end"
        :total="pagination.total"
        @current-change="() => getData()"
        @size-change="clickSearch"
      />
    </div>

    <!-- 指标数据折线图 -->
    <IndicatorDataCurveModal
      v-if="indicatorNumber"
      ref="indicatorDataCurveModalRef"
      :indicator-number="indicatorNumber"
    />

    <!-- 参数设置对话框 -->
    <ParameterSetting
      v-if="energyType && energyName"
      ref="parameterSettingRef"
      :energy-code="energyType"
      :energy-name="energyName"
      @ok="handleOk"
    />
  </div>
</template>
